package com.qb.hotelTV.network;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.qb.hotelTV.constants.AppConstants;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 网络管理器 - 优化版
 * 统一配置网络请求，支持缓存、重试、日志等功能
 */
public class NetworkManager {
    private static final String TAG = "NetworkManager";
    
    private static volatile NetworkManager instance;
    private ApiService apiService;
    private OkHttpClient okHttpClient;
    private Retrofit retrofit;
    
    private NetworkManager(Context context) {
        initNetworking(context);
    }
    
    public static NetworkManager getInstance(Context context) {
        if (instance == null) {
            synchronized (NetworkManager.class) {
                if (instance == null) {
                    instance = new NetworkManager(context.getApplicationContext());
                }
            }
        }
        return instance;
    }
    
    /**
     * 初始化网络配置
     */
    private void initNetworking(Context context) {
        // 配置Gson
        Gson gson = new GsonBuilder()
                .setLenient()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        
        // 配置日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> 
                Log.d(TAG, "HTTP: " + message));
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        
        // 配置OkHttpClient
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(AppConstants.HTTP_TIMEOUT_CONNECT, TimeUnit.MILLISECONDS)
                .readTimeout(AppConstants.HTTP_TIMEOUT_READ, TimeUnit.MILLISECONDS)
                .writeTimeout(AppConstants.HTTP_TIMEOUT_WRITE, TimeUnit.MILLISECONDS)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(new HeaderInterceptor())
                .addInterceptor(new RetryInterceptor(3)) // 重试3次
                .retryOnConnectionFailure(true)
                .build();
        
        // 配置Retrofit
        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        
        Log.d(TAG, "网络管理器初始化完成");
    }
    
    /**
     * 创建API服务（动态BaseUrl）
     */
    public ApiService createApiService(String baseUrl) {
        if (baseUrl == null || baseUrl.isEmpty()) {
            Log.w(TAG, "BaseUrl为空，使用默认配置");
            return getApiService();
        }
        
        // 确保baseUrl格式正确
        if (!baseUrl.startsWith("http")) {
            baseUrl = AppConstants.ApiConfig.BASE_URL_PREFIX + baseUrl;
        }
        if (!baseUrl.endsWith("/")) {
            baseUrl += "/";
        }
        
        Retrofit dynamicRetrofit = retrofit.newBuilder()
                .baseUrl(baseUrl)
                .build();
        
        return dynamicRetrofit.create(ApiService.class);
    }
    
    /**
     * 获取默认API服务
     */
    public ApiService getApiService() {
        if (apiService == null) {
            // 使用默认baseUrl，可以在需要时更改
            apiService = retrofit.newBuilder()
                    .baseUrl("http://default.api.com/")
                    .build()
                    .create(ApiService.class);
        }
        return apiService;
    }
    
    /**
     * 获取OkHttpClient实例（用于其他网络请求）
     */
    public OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }
    
    /**
     * 检查网络连接状态
     */
    public boolean isNetworkAvailable(Context context) {
        android.net.ConnectivityManager connectivityManager = 
                (android.net.ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        
        if (connectivityManager == null) return false;
        
        android.net.NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    
    /**
     * 清理资源
     */
    public void shutdown() {
        if (okHttpClient != null) {
            okHttpClient.dispatcher().executorService().shutdown();
            okHttpClient.connectionPool().evictAll();
        }
        Log.d(TAG, "网络管理器已关闭");
    }
} 